package com.woniuxy.house.web;

import com.woniuxy.house.entity.PictureChange;
import com.woniuxy.house.service.PictureChangeService;
import com.woniuxy.house.vo.ResponseEntity;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 轮播图
 * */
@RestController
@RequestMapping("/api/pictureChange")
public class PictureChangeController {
    @Value("${house.imagesavepath}")
    private String imageSavePath;
    @Autowired
    private PictureChangeService pictureChangeService;
    /**
     * 获取轮播图（参数控制图片数量）
     *
     * */

    @RequestMapping("/getPictures")
    public ResponseEntity getPictures(Integer size){
     return new ResponseEntity<>("200","ok",pictureChangeService.getLimitSize(size));

    }
    @RequestMapping("/addPictures")
    public ResponseEntity addPictures(@NotNull MultipartFile[] files) throws IOException {
        String[] names=null;
        for (int i = 0; i < files.length; i++) {
            //得到上传的图片
            String oldFileName=files[i].getOriginalFilename();
            if(!oldFileName.endsWith(".jpg")||!oldFileName.endsWith(".png")){
                return new ResponseEntity("400","文件格式错误",null);
            }
            //生成新文件名
            String name = UUID.randomUUID().toString().replace("-", "") + oldFileName.substring(oldFileName.lastIndexOf("."));
            String newName = imageSavePath + name;
            files[i].transferTo(new File(newName));
            names[i]=newName;
        }
        return new ResponseEntity("200","成功上传",names);


    }
    @RequestMapping("/deletePicture")
    public ResponseEntity deletePicture(@RequestBody PictureChange pictureChange){

        pictureChangeService.deleteById(pictureChange.getId());
        return ResponseEntity.SUCCESS;

    }
}
